package com.igeek.d0613.test2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhiyu
 * @Date:17:09
 * @DESC:
 */
public class Account {
    private double balance = 0.0;
    private Lock lock = new ReentrantLock();
    private Condition depositCondition = lock.newCondition();
    private Condition withdrawCondition = lock.newCondition();

    public void deposit(double amount) {
        lock.lock();
        try {
            while (balance > 0.0) {
                System.out.println(Thread.currentThread().getName() + "存款失败");
                depositCondition.await();
            }
            balance += amount;
            System.out.println(Thread.currentThread().getName() + " 存款 " + amount + " 元");
            withdrawCondition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void withdraw(double amount) {
        lock.lock();
        try {
            while (balance < amount) {
                System.out.println(Thread.currentThread().getName() + "取款失败，余额不足");
                withdrawCondition.await();
            }
            balance -= amount;
            System.out.println(Thread.currentThread().getName() + " 取款 " + amount + " 元");
            depositCondition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
